import 'package:flutter/material.dart';
import 'package:interview/components/app/app_text_button.dart';
import 'package:interview/components/page/page_empty.dart';
import 'package:interview/components/page/page_load_overlay.dart';
import 'package:interview/components/page/page_screen_half.dart';
import 'package:interview/components/question/question_list.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/providers/app_refresh_providers.dart';
import 'package:interview/servers/question_type.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';
import 'package:interview/views/home/components/category_filter.dart';
import 'package:interview/views/home/components/category_tabbar.dart';
import 'package:provider/provider.dart';


class HomeCategory extends StatefulWidget {
  const HomeCategory({super.key});

  @override
  State<HomeCategory> createState() => _HomeCategoryState();
}

class _HomeCategoryState extends State<HomeCategory> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int currentIndex = 0; // 当前选择试题频道
  List<QuestionType> categoryList = []; // 用于存储分类数据
  bool _isLoading = true; // 控制加载状态
  int sort = 0; // 当前筛选分类
  bool isInitialLoading = true; // 新增的标志，用于判断是否是初始加载  登录成功后不显示loading

  @override
  void initState()  {
    super.initState();
    _initializeData(isInitialLoading: true);
  }

  /// 初始化试题分类数据的方法
  Future<void> _initializeData({bool isInitialLoading = false}) async {
    final progressNotifier = ValueNotifier<double>(0.0);
    if(isInitialLoading){
      /*   显示加载框并绑定进度通知器
      WidgetsBinding.instance.addPostFrameCallback：  addPostFrameCallback 保证加载框的逻辑不会因为频繁触发 build() 而多次插入
      用于在当前帧的构建完成后执行一段逻辑，避免在组件构建过程中直接对 UI 产生副作用（如操作 Overlay 等）。
      在这里用于异步控制加载框的显示和隐藏，而不是让构建逻辑直接处理这些操作。
      */
      WidgetsBinding.instance.addPostFrameCallback((_) {
        PageLoadOverlay.show(context: context);
      });
    }
    
    try {
      // 获取分类数据
      final questionTypes = await fetchQuestionTypes(context);
      setState(() {
        categoryList = questionTypes;
        _isLoading = false;
        _tabController = TabController(length: categoryList.length, vsync: this);
      });
    } catch (e) {
      Logger.error('报错 $e', tag: "接口请求失败");
      setState(() {
        _isLoading = false; // 请求失败也停止加载
      });
    }finally {
      progressNotifier.dispose();
      if(isInitialLoading){
        // 隐藏加载框
        WidgetsBinding.instance.addPostFrameCallback((_) {
          PageLoadOverlay.hide();
        });
      }
    }
  }


  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void onTabTapped(int index) {
    setState(() {
      currentIndex = index;
      if (_tabController.index != index) {
        _tabController.animateTo(index);
      }
    });
  }

  void updateSort(int newSort) {
    setState(() {
      sort = newSort; // 更新排序方式
    });
  }

  void updateCurrentIndex(int newIndex) {
    setState(() {
      currentIndex = newIndex; // 更新当前索引
      if (_tabController.index != newIndex) {
        _tabController.animateTo(newIndex); // 同步更新 TabController
      }
    });
  }


  Future <void> filterTapped (ThemeData themeData) async {
    final theme = themeData.extension<AppColors>()!;
    // 临时变量用于存储筛选结果
    int? tempSort;
    int? tempIndex;
    bool? modalRes = await PageScreenHalf.showHalfScreenModal(
      context,
      dismissible: true,
      content: Center(
        child: CategoryFilter(
          categoryList: categoryList,
          sort:sort,
          currentIndex:currentIndex,
          onSortChanged: (newSort){
            tempSort = newSort;
          }, // 传递更新排序的回调函数
          onIndexChanged: (newInd){
            tempIndex = newInd;
          }, // 传递更新索引的回调函数
        ),
      ),
      showButtons: true,
      buttons: [
        AppTextButton(
          text: "重置", 
          textColor: theme.contrastMix3!,
          backgroundColor: theme.subjectMix1,
          onPressed: (){
            setState(() {
              updateSort(AppEnumSortType.sortDefault);
              updateCurrentIndex(0);
            });
            Navigator.of(context).pop();
          }
        ),
        const SizedBox(height: 6),
        AppTextButton(
          text: "完成", 
          textColor: theme.textColour1!,
          backgroundColor: theme.subjectMix2,
          onPressed: (){
            Navigator.of(context).pop(true);
          }
        ),
      ]
    );
    if (modalRes != null) {
      if (modalRes) {
        if (tempSort != null && tempSort != sort) {
          updateSort(tempSort!); // 更新排序方式
        }
        if (tempIndex != null && tempIndex != currentIndex) {
          updateCurrentIndex(tempIndex!); // 更新索引
        }
        Logger.info("确定$sort , $currentIndex ", tag: "ScreenModal");
      } else {
        Logger.info("取消", tag: "ScreenModal");
      }
    } else {
      Logger.info("对话框关闭", tag: "ScreenModal");
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    // 避免在build函数中 使用 addPostFrameCallback  
    if (_isLoading) {
      // 返回一个空容器，因为加载框是通过 Overlay 控制的  SizedBox.shrink() 是一个非常轻量的组件，几乎不占用任何渲染资源。  这样做的效果 降低首桢渲染200ms
      // 也可以做成骨架屏 但是骨架屏本身也会占用渲染资源
      return const SizedBox.shrink();
    }
    if (categoryList.isEmpty) {
      return const PageEmpty();
    }
    return Consumer<AppRefreshProvider>(
      builder: (context, refreshNotifier , child) { 
        if(refreshNotifier.shouldRefresh && mounted){
          WidgetsBinding.instance.addPostFrameCallback((_) {
          });
        }
        return Column(
          children: [
            // 顶部 TabBar 和筛选按钮
            CategoryTabbar(
              categoryList: categoryList,
              theme: theme,
              tabController: _tabController,
              onTabTapped: onTabTapped,
              onFilterTapped: () {
                // 处理筛选逻辑
                filterTapped(theme);
              },
            ),
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: categoryList.map((category) {
                  return QuestionList(
                    typeId:category.id,
                    sort:sort,
                  );
                }).toList(),
              ),
            ),
          ],
        );
      },
    );
  }
}




